package com.hkts.management.cargo.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkts.management.cargo.entity.HktsCargo;
import com.hkts.management.cargo.service.IHktsCargoService;
import com.hkts.management.common.utils.CustomPage;
import com.hkts.management.common.utils.Result;
import com.hkts.management.feign.FeignInterface;
import com.hkts.management.model.DTO.HktsCargoDTO;
import com.hkts.management.model.DTO.HktsCargoTo;
import com.hkts.management.model.DTO.PcCargoDTO;
import com.hkts.management.model.TO.HontUserTo;
import com.hkts.management.model.result.ResultData;
import com.hkts.management.properties.HistoryProperties;
import com.hkts.management.utils.CustomPageUtils;
import com.hkts.management.common.utils.ResultUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import springfox.documentation.annotations.ApiIgnore;

import javax.naming.Name;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author hml
 * @since 2021-04-22
 */
@RestController
@RequestMapping("/order/hktsCargo")
@Api(tags = "货源管理接口")
public class HktsCargoController {
    private final Logger logger = LoggerFactory.getLogger(HktsCargoController.class);

    @Autowired
    public IHktsCargoService iHktsCargoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FeignInterface feignInterface;

    /**
     * 分页查询数据
     *
     * @param page      分页信息
     * @param hktsCargo 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getHktsCargoPageList")
    public Result<Object> getHontUserList(Page<HktsCargo> page, HktsCargo hktsCargo) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsCargoService.selectPage(page, hktsCargo)));
    }



    /**
     * 保存和修改公用的
     *
     * @param hktsCargo 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsCargoSave")
    public Result<Object> hktsCargoSave(HktsCargo hktsCargo) {
        iHktsCargoService.saveOrUpdate(hktsCargo);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/hktsCargoGetById")
    public Result<Object> hktsCargoGetById(String id) {
        HktsCargo byId = iHktsCargoService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsCargoDelete")
    public Result<Object> hontUserDelete(String id) {
        iHktsCargoService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsCargoBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iHktsCargoService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }

    /**
     * 手机端查询分页货源列表
     *
     * @param page      分页信息
     * @param hktsCargoDTO 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getHktsCargoPageListOnPhone")
    @ApiOperation(value = "货源列表")
    public Result<Object> getHktsCargoPageListOnPhone(Page page, HktsCargoDTO hktsCargoDTO) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsCargoService.getHktsCargoPageListOnPhone(page, hktsCargoDTO)));
    }
    /**
     * 通过货源id获取货源详情
     * @param cargoId
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getCargoDetailById")
    @ApiOperation(value = "货源详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "cargoId", value = "货源id", required = true, dataType = "string")})
    public Result<Object> getCargoDetailById(String cargoId) {
        ResultData cargoDetailById = iHktsCargoService.getCargoDetailById(cargoId);
        return ResultUtil.data(cargoDetailById);
    }

    /**
     * 获取两地间距离
     * @param startArea
     * @param endArea
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getDistance")
    @ApiOperation(value = "获取两地间距离")
    @ApiImplicitParams({@ApiImplicitParam(name = "startArea", value = "装货地", required = true, dataType = "string"),
            @ApiImplicitParam(name = "endArea", value = "卸货地", required = true, dataType = "string")})
    public Result<Object> getDistance(String startArea,String endArea){
        BigDecimal distance = iHktsCargoService.getDistance(startArea, endArea);
        return ResultUtil.data(distance);
    }

    /**
     *
     * @param page
     * @param cargoId
     * @return
     */
    @GetMapping("/getApplyPageList")
    @ApiOperation(value = "报名列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "cargoId", value = "货源id", required = true, dataType = "string")})
    public Result<Object> getApplyPageList(Page page,@ApiParam(value = "货源id")String cargoId){
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsCargoService.getOrdersPageByApply(page,cargoId)));
    }
    @GetMapping("/getApplyPageListByStatus")
    @ApiOperation(value = "报名列表Pc")
    @ApiImplicitParams({@ApiImplicitParam(name = "cargoId", value = "货源id", required = true, dataType = "string"),
            @ApiImplicitParam(name = "checkStatus", value = "报名状态", required = true, dataType = "string")
    })
    public Result<Object> getApplyPageListByStatus(Page page,@ApiParam(value = "货源id")String cargoId, @ApiParam(value = "报名状态")String checkStatus){
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsCargoService.getOrdersPageByApplyPc(page,cargoId,checkStatus)));
    }

    /**
     * 发布货源
     * @param hktsCargoTo
     * @return
     */
    @ResponseBody
    @PostMapping("/saveHktsCargo")
    @ApiOperation(value = "发布货源")
    public Result<HktsCargo> saveHktsCargo(@RequestBody HktsCargoTo hktsCargoTo){

        return iHktsCargoService.saveCargoAndLabelAndDetail(hktsCargoTo);
    }

    /**
     * 货源编辑
     */
    /*@ResponseBody
    @PostMapping("/updateHktsCargo")
    @ApiOperation(value = "货源编辑")
    public Result<Object> updateHktsCago(@RequestBody HktsCargoTo hktsCargoTo){
        Result result = iHktsCargoService.updateCargoAndLabelAndDetail(hktsCargoTo);
        return result;
    }*/

    /**
     * 关闭货源
     * @param cargoId
     * @return
     */
    @PostMapping("/updateCagoStatus")
    @ApiOperation(value = "关闭货源")
    @ApiImplicitParams({@ApiImplicitParam(name = "cargoId", value = "货源id", required = true, dataType = "string")})
    public Result<Object> updateHktsCagoStatus(String cargoId){
        iHktsCargoService.updateCagoStatus(cargoId);
        return ResultUtil.success("关闭成功");
    }

    /**
     * 装货卸货历史记录
     * @return
     */
    @GetMapping("/getLoadingHistory")
    @ApiOperation(value = "装货卸货历史记录")
    @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "装货类型", required = true, dataType = "string")})
    public Result<Object> getLoadingHistory(String type){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        if (type.equals("loading")){
            List<Map<String,String>> range = redisTemplate.opsForList().range(HistoryProperties.CARGO_HISTORY_LOADING + hontUserTo.getId(), 0, -1);
            return ResultUtil.data(range);
        }
        List<Map<String,String>> range = redisTemplate.opsForList().range(HistoryProperties.CARGO_HISTORY_UNLOAD + hontUserTo.getId(), 0, -1);
        return ResultUtil.data(range);
    }

    /**
     * 装货卸货历史记录删除
     * @param index
     * @param type
     * @return
     */
    @PostMapping("/deleteHistory")
    @ApiOperation(value = "装货卸货历史记录删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "index", value = "下标", required = true, dataType = "int"),
            @ApiImplicitParam(name = "type", value = "装货类型", required = true, dataType = "string")
    })
    public Result<Object> deleteHistory(Integer index,String type){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        if (type.equals("loading")){
            List<Map<String,String>> range = redisTemplate.opsForList().range(HistoryProperties.CARGO_HISTORY_LOADING + hontUserTo.getId(), 0, -1);
            Map<String, String> stringStringMap = range.get(index);
            Long remove = redisTemplate.opsForList().remove(HistoryProperties.CARGO_HISTORY_LOADING + hontUserTo.getId(), 1, stringStringMap);
            Collections.reverse(range);
            return ResultUtil.data(remove);

        }
        List<Map<String,String>> range = redisTemplate.opsForList().range(HistoryProperties.CARGO_HISTORY_UNLOAD + hontUserTo.getId(), 0, -1);
        Map<String, String> stringStringMap = range.get(index);
        Long remove = redisTemplate.opsForList().remove(HistoryProperties.CARGO_HISTORY_UNLOAD + hontUserTo.getId(), 1, stringStringMap);
        Collections.reverse(range);
        return ResultUtil.data(remove);
    }

    /**
     * 无需token
     * @param id
     * @param lat
     * @param lon
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getCargoDetail")
    public Result<ResultData> getCargoDetailById(String id,String lat,String lon) {
        ResultData byId = iHktsCargoService.getCargoDetailById(id,lat,lon);
        return ResultUtil.data(byId);
    }

    /**
     * 特殊要求历史记录
     * @return
     */
    @GetMapping("/getRemarkHistory")
    @ApiOperation(value = "特殊要求历史记录")
    public Result<Object> getRemarkHistory(){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        List<Map<String,String>> range = redisTemplate.opsForList().range(HistoryProperties.CARGO_HISTORY_REMARK + hontUserTo.getId(), 0, -1);
        return ResultUtil.data(range);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/deleteRemarkHistory")
    public Result<Object> deleteRemarkHistory(String item) {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        if(StringUtils.isNotBlank(item)){
            List<String> range = redisTemplate.opsForList().range(HistoryProperties.CARGO_HISTORY_REMARK + hontUserTo.getId(), 0, -1);
            Iterator<String> iterator = range.iterator();
            while (iterator.hasNext()){
                if(iterator.next().equals(item)){
                    iterator.remove();
                }
            }
            redisTemplate.delete(HistoryProperties.CARGO_HISTORY_REMARK + hontUserTo.getId());
            if (range.isEmpty()){
                return ResultUtil.success("删除成功！");
            }
            redisTemplate.opsForList().rightPushAll(HistoryProperties.CARGO_HISTORY_REMARK + hontUserTo.getId(), range);

        }else{
            redisTemplate.delete(HistoryProperties.CARGO_HISTORY_REMARK + hontUserTo.getId());
        }
        return ResultUtil.success("删除成功");
    }
    @GetMapping("/getTimeZone")
    @ApiOperation(value = "时区")
    public Result<String> getTimeZone(){
        TimeZone aDefault = TimeZone.getDefault();
        return ResultUtil.data(aDefault.toString());
    }

    @ResponseBody
    @GetMapping("/getHktsCargoPageListOnPhonePc")
    @ApiOperation(value = "货源列表Pc")
    public Result<Object> getHktsCargoPageListOnPhonePc(Page page, PcCargoDTO pcCargoDTO) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsCargoService.getHktsCargoPageListOnPhonePc(page, pcCargoDTO)));
    }
    @GetMapping("/getOrderPageListByCargoId")
    @ApiOperation(value = "根据货源id查询运单列表Pc")
    @ApiImplicitParams({@ApiImplicitParam(name = "cargoId", value = "货源id", required = true, dataType = "string"),
            @ApiImplicitParam(name = "checkStatus", value = "运单状态", required = true, dataType = "string")
    })
    public Result<Object> getOrderPageListByCargoId(Page page,@ApiParam(value = "货源id")String cargoId, @ApiParam(value = "运单状态")String orderStatus){
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsCargoService.getOrderPageListByCargoId(page, cargoId,orderStatus)));
    }

    /**
     * 报名信息与运单信息中数据
     * @return
     */
    @GetMapping("/getApplyCount")
    @ApiOperation(value = "报名信息与运单信息中数据")
    public Result<Object> getApplyCount(String cargoId){
        return ResultUtil.data(iHktsCargoService.getApplyCountAndWeight(cargoId));
    }

    @GetMapping("/selectByTitle")
    @ApiOperation(value = "报名信息与运单信息中数据")
    public Result<Object> selectByTitle(){
        return ResultUtil.data(iHktsCargoService.selectListByTitle());
    }

    /**
     * 订单信息
     * @return
     */
    @GetMapping("/getOrderData")
    @ApiOperation(value = "订单信息")
    public Result<Object> getOrderData(String cargoId){
        return ResultUtil.data(iHktsCargoService.getOrderData(cargoId));
    }
}
